
import ac.qnlm.antlr.CPP14Lexer;
import ac.qnlm.antlr.CPP14Parser;
import ac.qnlm.listener.firstTraverseListener;
import ac.qnlm.listener.secondTraverseListener;
import ac.qnlm.util.Utility;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class kernelTranslator {

    private static Logger mLogger = LogManager.getLogger(kernelTranslator.class.getName());

    public static void main(String[] args) throws Exception {

        String filename = null;
        File outputFile;
        filename = args[0];
        Utility utility = new Utility();

        File fileobj = new File(filename);
        if(fileobj.isDirectory())
            throw new Exception("传入目录非法，请重新输入");
        mLogger.info("input file: " +fileobj.toString());

        Calendar Cld = Calendar.getInstance();
        Date date = Cld.getTime();
        mLogger.info(new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss:SSS").format(date));

//        InputStream is = System.in;
//        Vector<InputStream> streams = new Vector<>();
//        is = new FileInputStream(fileobj);
//        streams.add(is);
//        SequenceInputStream allinput = new SequenceInputStream(streams.elements());
//        ANTLRInputStream input = new ANTLRInputStream(allinput);

        CharStream input = CharStreams.fromFileName(filename);

        CPP14Lexer lexer = new CPP14Lexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        CPP14Parser parser = new CPP14Parser(tokens);
        parser.setBuildParseTree(true);
        ParseTree tree = parser.translationunit(); // parse

        // first traverse
        ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker
        firstTraverseListener cudaFirstActor = new firstTraverseListener(parser, utility, tokens);
        walker.walk(cudaFirstActor, tree); // initiate walk of tree with listener
        mLogger.info(cudaFirstActor.getclass(tree));

        //second traverse
     //   secondTraverseListener cudaSecondActor = new secondTraverseListener(cudaFirstActor.classout,utility, tokens);
     //   walker.walk(cudaSecondActor, tree); // initiate walk of tree with listener

        outputFile = new File("swKernel.c");
        OutputStream out = new FileOutputStream(outputFile);
        String context = cudaFirstActor.getclass(tree);
        byte[] bytes = context.getBytes("UTF-8");
        out.write(bytes);
        out.close();

    }

}